# coding:utf-8
import re, smtplib, traceback, paramiko
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def send_email(subject, msg, fromemail, toemail, password):
    obj = MIMEMultipart()
    if not isinstance(subject, unicode):
        subject = unicode(subject, "utf-8")
    obj["Subject"] = subject
    obj["From"] = fromemail
    obj["To"] = ",".join(toemail)
    obj.attach(MIMEText(msg, "html", "utf-8"))
    try:
        s = smtplib.SMTP()
        s.connect("smtp.kill.com.cn", 28)  # SMTP服务器地址及端口号
        s.login(fromemail, password)
        s.sendmail(fromemail, toemail, obj.as_string())
        s.quit()
    except Exception as err:
        print err
        print traceback.format_exc()


def login_and_exec(hostname, username, password, port):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username=username, password=password, port=port)
        x, y, z = ssh.exec_command('free -m')  # 双引号导致命令无法执行
    except Exception as e:
        print e
    return y.read()



servers = [{"hostname": "localhost", "username": "awp", "password": "awp", "port": 22},]
for i in servers:
    command_rst = login_and_exec(i["hostname"], i["username"], i["password"], i["port"])
    pat = "(\d+)\s+(\d+)"
    rst = re.compile(pat).findall(command_rst)
    free = int(rst[0][0]) - int(rst[0][1])
    if free < 900:
        subject = "内存不足预警"
        msg = i["hostname"] + "的可用内存不足" + "%.2f" % (float(free)/float(rst[0][0]))
        fromemail = ""  # 添加发送者的邮箱地址
        toemail = ""  # 添加收件者的邮箱地址
        pwd = ""  # 发送方登录邮箱的密码
        send_email(subject, msg, fromemail, toemail, pwd)
